package cn.com.bluemoon.daps.common.toolkit;

import cn.com.bluemoon.daps.common.enums.DatabaseType;

import java.util.Arrays;

/**
 * 参考{@link com.alibaba.druid.DbType}
 *
 * @author Jarod.Kong
 * @date 2022/1/14 16:20
 */
public enum DbType {
    other,
    jtds,
    hsql,
    db2,
    postgresql,
    sqlserver,
    oracle,
    mysql,
    mariadb,
    derby,
    hive,
    impala,
    h2,
    dm,
    kingbase,
    gbase,
    oceanbase,
    informix,
    odps,
    teradata,
    phoenix,
    edb,
    kylin,
    sqlite,
    ads,
    presto,
    elastic_search,
    hbase,
    drds,
    clickhouse,
    blink,
    antspark,
    spark,
    oceanbase_oracle,
    polardb,
    ali_oracle,
    mock,
    sybase,
    highgo,
    ingres,
    cloudscape,
    timesten,
    as400,
    sapdb,
    kdb,
    log4jdbc,
    xugu,
    firebirdsql,
    JSQLConnect,
    JTurbo,
    interbase,
    pointbase,
    edbc,
    mimer,
    starrocks,
    doris_db,// 项目统称StarRocks和Doris为DorisDB
    doris;

    public static DbType valOf(DatabaseType databaseType) {
        if (databaseType == null) {
            return null;
        }
        DbType dbType = DbTypeHelper.getDbType(databaseType);
        if (dbType == null) {
             dbType = valOf(databaseType.name());
             if (dbType == null){
                 dbType = valOf(databaseType.getDbName());
             }
        }
        return dbType;
    }

    public static DbType valOf(String dbName) {
        if (dbName == null) {
            return null;
        }
        // 别名补充
        switch (dbName.toLowerCase()) {
            case "sap":
            case "hana":
                return DbType.sapdb;
            case "pgsql":
                return DbType.postgresql;
            case "es":
                return DbType.elastic_search;
            default:
                // 忽略大小写
                DbType dbType = Arrays.stream(values())
                        .filter(s -> s.name().equalsIgnoreCase(dbName))
                        .findFirst().orElseThrow(() -> new UnsupportedOperationException("不支持该数据库类型" + dbName));
                return dbType;
        }

    }

    public static DbType from(com.alibaba.druid.DbType druidDbType) {
        if (druidDbType == null) {
            return null;
        }
        return valOf(druidDbType.name());
    }

    public static com.alibaba.druid.DbType of(DbType dbType){
        if (dbType == null) {
            return null;
        }
        DbType db = valOf(dbType.name());
        return com.alibaba.druid.DbType.valueOf(db.name());
    }
}
